<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
$province_id = $city_id = '';
if (!empty($model->region_id)) {
    $region = \common\models\Region::findOne($model->region_id);
    $province_id = $model->region_id;
    if (!empty($region->pid)) {
        $province_id = $region->pid;
        $city_id = $model->region_id;
    }
}

/* @var $this yii\web\View */
/* @var $model common\models\ExhibitionHall */
/* @var $form yii\widgets\ActiveForm */
?>
<?=Html::jsFile('/static/common/js/ajaxfileupload.js')?>
<?=Html::jsFile('/static/common/js/underscore-min.js')?>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=ZubVDLGbR5Rduah7YW2acfLuGQIgxKse"></script>
<style>
.exhibition-hall-form {
    border: 1px solid #ddd;
}
.exhibition-hall-form .nav-tabs-custom>.nav-tabs {padding-left: 5px;background-color: #337ab7;}
.nav-tabs-custom>.nav-tabs>li>a,.nav-tabs-custom>.nav-tabs>li>a:hover {color: #fff;}
.picture-list {}
.picture-list .picture-item {
    position: relative;
    height: 200px;
    margin-bottom: 15px;
}
.picture-list .picture-item img {
    max-height: 192px;
}
.picture-list .add .picture_btn {
    display: none;
}
.picture-list .picture-item .picture_btn {
    display: none;
    position: absolute;
    bottom: 21px;
    left: 0;
    width: 100%;
    height: 40px;
    padding: 3px 0;
    background-color: rgba(0,0,0,0.3);
    overflow: hidden;
}
.picture-list .picture-item:hover .picture_btn {
    display: block;
}
</style>
<div class="exhibition-hall-form">

    <?php $form = ActiveForm::begin([
        'id' => 'client-form'
    ]); ?>
    <div class="nav-tabs-custom">
        <ul class="nav nav-tabs">
            <li class="active"><a href="#basic" data-toggle="tab" aria-expanded="true">基本信息</a></li>
            <li class=""><a href="#photo" data-toggle="tab" aria-expanded="false">展馆图片</a></li>
            <li class=""><a href="#video" data-toggle="tab" aria-expanded="false">视频介绍</a></li>
        </ul>
        <div class="tab-content">
            <div class="tab-pane active" id="basic">
                <table class="table">
                    <tr>
                        <td width="49%"><?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?></td>
                        <td><?= $form->field($model, 'status')->dropDownList(\common\helpers\TStringHelper::getStatusText()) ?></td>
                    </tr>
                    <tr>
                        <td width="49%">
                            <?= $form->field($model, 'banner')->textInput(['id' => 'banner_input']) ?>
                            <input type="file" name="Filedata" class="file_upload_attach" id="banner" data-thumb="1550,780" data-id="attach">
                        </td>
                        <td>
                            <?= $form->field($model, 'litpic')->textInput(['id' => 'litpic_input']) ?>
                            <input type="file" name="Filedata" class="file_upload_attach" id="litpic" data-thumb="285,225" data-id="attach">
                        </td>
                    </tr>
                    <tr>
                    <tr>
                        <td>
                            <div class="form-group">
                                <label class="control-label"><?=Yii::t('common', 'region')?></label>
                                <div class="form-group">
                                    <div class="hidden">
                                        <?= $form->field($model, 'region_id')->hiddenInput(['id' => 'region_id'])->label(false) ?>
                                    </div>
                                    <div class="row">
                                        <div class="col-xs-3 col-md-3 province">
                                            <select name="region[]" class="form-control region_id" id="province" onchange="getRegion(this, 'city')">
                                                <option value=""><?=Yii::t('common', 'select...')?></option>
                                            </select>
                                        </div>
                                        <div class="col-xs-3 col-md-3 city" style="display: none;">
                                        <!--<select name="region[]" class="form-control region_id" id="city" onchange="getRegion(this, 'area')">-->
                                            <select name="region[]" class="form-control region_id" id="city">
                                                <option value=""><?=Yii::t('common', 'select...')?></option>
                                            </select>
                                        </div>
                                        <!--div class="col-xs-3 col-md-3 area" style="display: none;">
                                            <select name="region[]" class="form-control region_id" id="area">
                                                <option value=""><?/*=Yii::t('common', 'select...')*/?></option>
                                            </select>
                                        </div>-->
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label" for="exhibitionhall-address">地址</label>
                                <div>
                                    <?= $form->field($model, 'address')->textInput(['maxlength' => true])->label(false) ?>
                                </div>
                                <div class="row row-fix" style="margin-top: 10px;">
                                    <div class="col-xs-4 col-sm-4">
                                        <?= $form->field($model, 'lng')->textInput(['id' => 'location_y', 'placeholder' => Yii::t('common', 'lng'), 'readonly' => 'readonly'])->label(false)?>
                                    </div>
                                    <div class="col-xs-4 col-sm-4">
                                        <?= $form->field($model, 'lat')->textInput(['id' => 'location_x', 'placeholder' => Yii::t('common', 'lat'), 'readonly' => 'readonly'])->label(false)?>
                                    </div>
                                    <div class="col-xs-4 col-sm-4">
                                        <?=Html::button('选择坐标', ['class' => 'btn btn-default', 'onclick' => 'showCoordinate(this)'])?>
                                    </div>
                                </div>
                            </div>
                        </td>
                        <td style="vertical-align: top">
                            <?= $form->field($model, 'hotpic')->textInput(['id' => 'hotpic_input'])->hint('列表页面Banner图片,300*470') ?>
                            <input type="file" name="Filedata" class="file_upload_attach" id="hotpic" data-thumb="300,470" data-id="attach">
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <?= $form->field($model, 'introduce')->widget(\dosamigos\ckeditor\CKEditor::className(),[
                                'options' => ['row' => 10],
                                'preset' => 'basic',
                                'clientOptions' => [
                                    'filebrowserUploadUrl' => \yii\helpers\Url::toRoute(['common/url', 'event' => 0]),
                                ]
                            ]) ?>
                        </td>
                    </tr>
                    <tr>
                        <td><?= $form->field($model, 'area')->textInput(['maxlength' => true])->hint('单位平方米') ?></td>
                        <td><?= $form->field($model, 'recommend')->radioList(\common\helpers\TStringHelper::getYesOrNo())->hint('即列表页面的热门') ?></td>
                    </tr>
                    <tr>
                        <td><?= $form->field($model, 'order')->textInput(['type' => 'number']) ?></td>
                        <td><?= $form->field($model, 'views_num')->textInput(['type' => 'number']) ?></td>
                    </tr>
                </table>
            </div>
            <!-- /.tab-pane -->
            <div class="tab-pane" id="photo">
                <p>注：图片大小380*300</p>
                <div class="picture-list clearfix">
                    <?php
                    $i = 1;
                    if (!empty($picture)) {
                        foreach ($picture as $val) {
                            ?>
                            <div class="col-xs-6 col-md-3 picture-item">
                                <a href="javascript:;" class="thumbnail"><img src="<?=$val['fileUrl']?>" onerror="this.src='/static/common/images/nopicture.png'" /></a>
                                <div class="picture_btn text-center">
                                    <div class="hidden">
                                        <textarea name="picture[]" class="picture_value" id="picture_<?=$i?>_input"><?=json_encode($val)?></textarea>
                                        <input type="file" name="Filedata" class="picture_upload" id="picture_<?=$i?>" data-id="attach">
                                    </div>
                                    <div class="btn-group">
                                        <button class="btn btn-large btn-primary picture_plus" type="button">上传</button>
                                        <button class="btn btn-large btn-danger picture_remove" type="button">删除</button>
                                    </div>
                                </div>
                            </div>
                            <?php
                            $i++;
                        }
                    }
                    ?>
                    <div class="col-xs-6 col-md-3 add" title="添加">
                        <a href="javascript:;" class="thumbnail"><img src="" onerror="this.src='/static/common/images/addpicture.png'" /></a>
                    </div>
                </div>
            </div>
            <!-- /.tab-pane -->
            <div class="tab-pane" id="video">
                <div class="form-group field-video_input">
                    <label class="control-label" for="banner_input">视频介绍</label>
                    <input type="hidden" id="video_name" class="form-control" name="video_name[]" value="<?=!empty($video[0])?$video[0]['filename']:''?>">
                    <input type="text" id="video_input" class="form-control" name="video[]" value="<?=!empty($video[0])?$video[0]['fileUrl']:''?>">
                    <div class="help-block"></div>
                </div>
                <input type="file" name="Filedata" class="file_upload_attach" id="video" data-extension=".mp4" data-thumb="" data-id="attach">
            </div>
            <!-- /.tab-pane -->
        </div>
    </div>

    <div class="form-group" style="padding-left: 30px;">
        <?= Html::submitButton($model->isNewRecord ? Yii::t('common', 'create') : Yii::t('common', 'update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary btn-lg', 'id' => 'submit']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>
<div id="map-dialog" class="modal fade in" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h3>请选择地点</h3>
            </div>
            <div class="modal-body" id="mapContainer"></div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="savePoint()">确认</button>
            </div>
        </div>
    </div>
</div>

<script type="text/template" id="picture_tpl">
    <div class="col-xs-6 col-md-3 picture-item">
        <a href="javascript:;" class="thumbnail"><img src="" onerror="this.src='/static/common/images/nopicture.png'" /></a>
        <div class="picture_btn text-center">
            <div class="hidden">
                <textarea name="picture[]" class="picture_value" id="picture_<%=obj.id%>_input"></textarea>
                <input type="file" name="Filedata" class="picture_upload" id="picture_<%=obj.id%>" data-id="attach">
            </div>
            <div class="btn-group">
                <button class="btn btn-large btn-primary picture_plus" type="button">上传</button>
                <button class="btn btn-large btn-danger picture_remove" type="button">删除</button>
            </div>
        </div>
    </div>
</script>

<script>
    $(function () {
        //此处用了change事件，当选择好图片打开，关闭窗口时触发此事件
        $(".file_upload_attach").change(function (e) {
            var val = e.target.value;
            var point = val.lastIndexOf(".");
            var type = val.substr(point).toLowerCase();
            var extension = $(this).data('extension');
            if (typeof extension != 'undefined' && extension != '' ) {
                if (type != extension) {
                    alert('系统目前只支持'+extension+'文件格式');
                    return false;
                }
            }else {
                if (type != ".jpg" && type != ".jpeg" && type != ".png") {
                    alert('系统目前只支持.jpg、.jpeg、.png、.mp4文件格式');
                    return false;
                }
            }
            var file_id = $(this).attr('id');
            var thumb = $(this).data('thumb');
            $.ajaxFileUpload({
                //处理图片的脚本路径
                url: '<?=\yii\helpers\Url::toRoute(['common/upload-thumb', 'event' => 1, 'dir' => 'hall'])?>&thumb='+thumb,
                type: 'post',       //提交的方式
                secureuri: false,   //是否启用安全提交
                fileElementId: file_id,     //file控件ID
                dataType: 'json',  //服务器返回的数据类型
                success: function (data, status) {  //提交成功后自动执行的处理函数
                    if (data.error) {
                        alert(data.msg);
                        return false;
                    } else {
                        $("#"+file_id+'_input').val(data.fileUrl);
                        if (file_id == 'video') {
                            $("#"+file_id+'_name').val(data.filename);
                        }
                    }
                },
                error: function (data, status, e) {   //提交失败自动执行的处理函数
                    alert(e);
                }
            })
        })

        /**-----------------------图片---------------------------**/
        var picture_count = <?=$i?>;
        $(".add").on('click', function (e) {
            var html = _.template($("#picture_tpl").html())
            $(this).before(html({id: picture_count}))
            picture_count ++;
        })

        $(document).on('click', ".picture_plus", function () {
            $(this).parents('.picture-item').find('.picture_upload').trigger('click');
        })
        $(document).on('click', ".picture_remove", function () {
            var parent = $(this).parents(".picture-item");
            //上传过图片的才提示
            if(parent.find(".picture_value").val() != '') {
                if (!confirm('确认删除？')) {
                    return false;
                }
            }
            $(this).parents('.picture-item').remove();
        })
        $(document).on("change", ".picture_upload", function (e) {
            var val = e.target.value;
            var point = val.lastIndexOf(".");
            var type = val.substr(point).toLowerCase();
            if (type != ".jpg" && type != ".jpeg" && type != ".png") {
                alert('系统目前只支持.jpg、.jpeg、.png文件格式');
                return false;
            }
            var images = $(this).parents('.picture-item').find('img');
            var file_id = $(this).attr('id');
            var file_input = $("#"+file_id+'_input');
            $.ajaxFileUpload({
                //处理图片的脚本路径
                url: '<?=\yii\helpers\Url::toRoute(['common/upload-thumb', 'event' => 1, 'dir' => 'hall', 'thumb' => '380,300'])?>',
                type: 'post',       //提交的方式
                secureuri: false,   //是否启用安全提交
                fileElementId: file_id,     //file控件ID
                dataType: 'json',  //服务器返回的数据类型
                success: function (data, status) {  //提交成功后自动执行的处理函数
                    if (data.error) {
                        alert(data.msg);
                        return false;
                    } else {
                        file_input.text(JSON.stringify(data));
                        images.attr('src', data.fileUrl);
                    }
                },
                error: function (data, status, e) {   //提交失败自动执行的处理函数
                    alert(e);
                }
            })
        })

        /**-----------------------图片---------------------------**/

        $("#submit").on('click', function(){
            var region_id = $("select[name='region[]']").map(function (e) {
                return $(this).val();
            }).get().join(',');
            if (region_id == ',') {
                alert('请选择地区信息');
                return false;
            }
            var region = region_id.split(',');
            var tmp_region_id = typeof region[0] == 'undefined' ? region : region[0];
            if (typeof region != "undefined" && typeof region[1] != 'undefined' && region[1] != '') tmp_region_id = region[1];
            $("#region_id").val(tmp_region_id);
            $("#client-form").data('yiiActiveForm').validated = true;
        })
    })

    getRegion(0, 'province');
    function getRegion(obj, id){
        var pid = typeof obj == 'object' ? obj.value : obj;
        pid = typeof pid == 'undefined' || pid == '' ? 0 : pid;
        $.get("<?=Yii::$app->urlManager->createUrl(['/../common/get-region'])?>", {pid: pid}, function (response) {
            if (response.code == 0) {
                var data = response.data;
                var html = '';
                if (data !='' && typeof data == 'object') {
                    html += '<option value=""><?=Yii::t('common', 'select...')?></option>';
                    for (var i in data) {
                        var selectd = false;
                        <?php
                        if (!empty($province_id)){
                        ?>
                        if (id == 'province' && i == parseInt('<?=$province_id?>')){
                            selectd = true;
                        }
                        <?php
                        }
                        ?>
                        <?php
                        if (!empty($city_id)){
                        ?>
                        if (id == 'city' && i == parseInt('<?=$city_id?>')){
                            selectd = true;
                        }
                        <?php
                        }
                        ?>
                        html += '<option value="'+i+'" '+(selectd?'selected="selected"':'')+'>'+data[i]+'</option>';
                    }
                    $("#"+id).html(html).parent().show();
                }else {
                    $("#" + id).html(html).parent().hide();
                }
            }
        }, 'json')
    }
    <?php
    if (!empty($city_id)){
    ?>
    getRegion(<?=$province_id?>, 'city');
    <?php
    }
    ?>

    function showCoordinate(obj) {
        var lng = $("#location_y").val();
        var lat = $("#location_x").val();
        $("#map-dialog").modal('show');
        $.get("<?=Yii::$app->urlManager->createUrl(['common/map'])?>", {lng: lng, lat: lat}, function(response){
            $("#mapContainer").empty().html(response);
        })
    }

    function savePoint(){
        //$("#exhibitionhall-address").val($("#suggestId").val());
        $("#location_y").val(point.lng);
        $("#location_x").val(point.lat);
        $("#map-dialog").modal('hide');
        $("#mapContainer").empty();
    }
</script>
